<?php

namespace App\Http\Controllers;

use App\Models\ContentArticleModel;
use App\Models\ContentModel;
use App\Models\DoctorModel;
use App\Models\DoctorPatientModel;
use App\Models\PatientModel;
use Doctrine\Inflector\Rules\Word;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use EasyWeChat\Work\GroupRobot\Messages\Markdown;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpWord\Reader\Word2007;

class TestController extends Controller
{

    private $classId = 99;
    protected $gitignore = [
        'dtrd_ent_rd_tools', // 工具箱（有初始化数据）
    ];

    public function test()
    {
        dd("ok");
        $name = "降糖药物";
        $array = [
            "并发症防治" => 31,
            "合理运动" => 3,
            "降糖药物" => 30,
            "逆糖饮食" => 1,
            "糖尿病逆转" => 14,
            "糖尿病知识" => 84,
            "血糖检测" => 12,
            "中医调理" => 83,
            "会议资讯" => 22,
            "医学前沿" => 10,
            "医学知识" => 23,
            "诊疗指南" => 17,
        ];

        $this->classId = $array[$name];
        var_dump($this->classId);

        $wordsPath = '/var/www/html/dtrd-qywechat/public/words/'.$name;
        // 获取所有的文章列表
        $list = [];
        $title = [];
        $errorTitle = [];
        $this->find_files(public_path('/words/'.$name), $list);
        foreach ($list[$wordsPath] as $k => $item) {
            $title[] = [
                'title' => str_replace('.docx', '', $item),
                'path' => $wordsPath.'/'.$item,
            ];
        }

        // dd($title);

        // DB::beginTransaction();
        foreach ($title as $article) {

            $value = $article['title'];
            $path = $article['path'];


            // dd($this->wordParsing($path));
            try {
                $content = $this->getWord($path);
            } catch (\Exception $e) {
                $errorTitle[] = $article['title'];
                continue;
            }
            foreach ($content as $k => &$c) {
                if (strpos($c,'<img src="data:image/jpeg;base64') === false) {
                    $c = "<p class=\"15\" style=\"line-height: 2;\"><span style=\"font-size: 18pt;\"><span style=\"font-family: 宋体;\"><span style=\"font-family: 宋体;\">".$c."</span></span></span></p>";
                } else {
                    preg_match('/base64,([^"]+)"/', $c, $m);
                    $base64Img = $m[1];
                    // dd($base64Img);
                    $time = time();
                    Storage::disk('article')->put($time.'.jpg', base64_decode($base64Img));
                    if ($k == 0) {
                        $cover = "https://img.dtx-tech.com/article/{$time}.jpg";
                        unset($content[$k]);
                    } else {
                        $c  = "<img src=\"https://img.dtx-tech.com/article/{$time}.jpg\">";
                    }
                }
            }

            DB::beginTransaction();
            try {
                $contentModel = new ContentModel();
                $contentModel->title = $value;
                $contentModel->class_id = $this->classId;
                $contentModel->time = time();
                $contentModel->sequence = 0;
                $contentModel->status = 1;
                $contentModel->image = $cover ?? '';
                $contentModel->copyfrom = '本站';
                $contentModel->views = 0;
                $contentModel->taglink = 0;
                $contentModel->site = 1;
                $contentModel->top_mark = 0;
                $contentModel->view = 0;
                $contentModel->is_del = 0;
                $contentModel->course_type = 1;

                $contentModel->save();
                $contentId = $contentModel->content_id;
                $contentModel->url = 'http://dtrd.h5.dtx-tech.com/article.html?articleId='.$contentId;
                $contentModel->save();

                $contentArticleModel = new ContentArticleModel();
                $contentArticleModel->content_id = $contentId;
                $contentArticleModel->content = implode('', $content);
                $contentArticleModel->save();

                // $contentModel->article()->create([
                //     'content' => implode('', $content)
                // ]);

                // unlink($path);

            } catch (\Exception $e) {
                DB::rollBack();
            }

            DB::commit();
            // dd();

        }

        dd("{$name} 共有".count($title)."篇文章，导入失败".count($errorTitle)."篇，导入失败列表为：" . implode('，', $errorTitle));

    }

    function getC($path) {
        //读取HTML内容
        $document=new \DOMDocument();
        $document->loadHTML(file_get_contents($path));
        $html=simplexml_import_dom($document);
        return ((array)$html->body);

    }


    function readDocx($file_tempName = '')
    {
        $content = '';
        $zip = zip_open($file_tempName);
        if (!$zip || is_numeric($zip)) return false;
        while ($zip_entry = zip_read($zip)) {
            if (zip_entry_open($zip, $zip_entry) == FALSE) continue;
            if (zip_entry_name($zip_entry) != "word/document.xml") continue;
            $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
            zip_entry_close($zip_entry);
        }
        zip_close($zip);
        $content = str_replace([PHP_EOL],'',$content);
        $content = str_replace(["\n","\t","\r"], "", $content);
        $content = strip_tags($content);
        return $content;
    }


    private function getContent($path, $title)
    {
        // $word = new Word2007();
        // //WORD转换HTML
        // $result=$word->load($path);
        // $write=new \PhpOffice\PhpWord\Writer\HTML($result);
        // $write->save(storage_path().$title.'.html');
        //读取HTML内容
        $document=new \DOMDocument();
        $document->loadHTML($path);
        // $document->loadHTML(file_get_contents(storage_path().$title.'.html'));
        $html=simplexml_import_dom($document);
        return ((array)$html->body);
    }


    function find_files($dir, &$dir_array)
    {
        // 读取当前目录下的所有文件和目录（不包含子目录下文件）
        $files = scandir($dir);

        if (is_array($files)) {
            foreach ($files as $val) {
                // 跳过. 和 ..
                if ($val == '.' || $val == '..')
                    continue;

                // 判断是否是目录
                if (is_dir($dir . '/' . $val)) {
                    if (strpos($val, 'doc')) {
                        $dir_array[$dir][] = $val;
                    }
                    // 将当前目录添加进数组
                    // $dir_array[$dir][] = $val;
                    // 递归继续往下寻找
                    // $this->find_files($dir . '/' . $val, $dir_array);
                } else {
                    // 不是目录也需要将当前文件添加进数组
                    $dir_array[$dir][] = $val;
                }
            }
        }
    }


    //解析word内容并返回html
    public function wordParsing($source)
    {
        //加载word文件 并 通过getSections获取word文档的全部元素
        $sections = \PhpOffice\PhpWord\IOFactory::load($source)->getSections();

        //定义html变量用于存储word文本内容
        $html = '';

        //循环所有元素
        foreach ($sections as $section) {

            //获取当前元素的所有子元素
            $elements = $section->getElements();

            //循环当前子元素
            foreach ($elements as $eky => $evl) {
                $html .= '<p>';
                if ($evl instanceof \PhpOffice\PhpWord\Element\TextRun) { //判断是否普通文本

                    $content_elements = $evl->getElements();
                    foreach ($content_elements as $eky2 => $evl2) {
                        $html .= $this->elementHandler($evl2, $evl);
                    }

                } elseif ($evl instanceof \PhpOffice\PhpWord\Element\PreserveText) { //判断是否保留元素(如自动生成链接的网址元素)
                    $data = $evl->getText();
                    $find = array('{', 'HYPERLINK', '}', ' ', '"', 'f', 'g');
                    $replace = '';
                    $resText = str_replace($find, $replace, $data);
                    if (isset($resText)) {
                        $html .= $resText[0];
                    }
                } elseif ($evl instanceof \PhpOffice\PhpWord\Element\Table) {
                    $all_table_elements = $evl->getRows();
                    $html .= '<table style="margin:0;padding:0;border-collapse:collapse;border-spacing:0;" >';
                    foreach ($all_table_elements as $tky => $tvl) {
                        $html .= '<tr style="padding:0">';
                        $all_table_cells = $tvl->getCells();
                        foreach ($all_table_cells as $cky => $cvl) {
                            $cell_elements = $cvl->getElements();

                            //获取表格宽度(返回单位为：缇)
                            $td_width = $cvl->getWidth();
                            $td_width_px = round($cvl->getWidth() / 15, 0);

                            $html .= '<td style="border: 1px solid #777777;padding:2px 5px;width:' . $td_width_px . '">';
                            foreach ($cell_elements as $cl) {

                                //判断当存在elements属性时执行
                                if (property_exists($cl, 'elements')) {
                                    $content_elements = $cl->getElements();
                                    foreach ($content_elements as $eky2 => $evl2) {
                                        $html .= $this->elementHandler($evl2, $cl);
                                    }
                                }

                            }
                            $html .= '</td>';
                        }
                        $html .= '</tr>';
                    }
                    $html .= '</table>';
                }
                $html .= '</p>';
            }
            return $html;

        }
    }

    //元素内容数据处理，$end_element最末级元素，是$parent_element的子元素；$parent_element为当前元素
    public function elementHandler($end_element, $parent_element)
    {
        $html = '';
        if ($end_element instanceof \PhpOffice\PhpWord\Element\Text) { //判断是否普通文本

            $style = $end_element->getFontStyle();
            //$fontFamily = mb_convert_encoding($style->getName(), 'GBK', 'UTF-8');
            $fontFamily = $style->getName();
            $fontSize = $style->getSize() ? ($style->getSize() / 72) * 96 : '';
            $isBold = $style->isBold();
            $fontcolor = $style->getColor();
            $styleString = '';
            $fontFamily && $styleString .= "font-family:{$fontFamily};";
            $fontSize && $styleString .= "font-size:{$fontSize}px;";
            $isBold && $styleString .= "font-weight:bold;";
            $fontcolor && $styleString .= "color:{$fontcolor};";
            $html .= sprintf('<span style="%s">%s</span>',
                $styleString, $end_element->getText()
            //mb_convert_encoding($evl2->getText(), 'GBK', 'UTF-8')
            );//dump($end_element->getText());

        } elseif ($end_element instanceof \PhpOffice\PhpWord\Element\Link) {  //判断是否链接
            $style = $end_element->getFontStyle();
            //$fontFamily = mb_convert_encoding($style->getName(), 'GBK', 'UTF-8');
            $fontFamily = $style->getName();
            $fontSize = $style->getSize() ? ($style->getSize() / 72) * 96 : '';
            $isBold = $style->isBold();
            $fontcolor = $style->getColor();
            $styleString = '';
            $fontFamily && $styleString .= "font-family:{$fontFamily};";
            $fontSize && $styleString .= "font-size:{$fontSize}px;";
            $isBold && $styleString .= "font-weight:bold;";
            $fontcolor && $styleString .= "color:{$fontcolor};";
            $html .= sprintf('<a href="%s" style="%s">%s</a>',
                $end_element->getSource(), $styleString, $end_element->getText()
            //mb_convert_encoding($evl2->getText(), 'GBK', 'UTF-8')
            );

        } elseif ($end_element instanceof \PhpOffice\PhpWord\Element\Image) { //判断是否图片
            //可以在这里执行自定义方法将图片上传到OSS或者图片服务器哈
            $imageDataTmp = $end_element->getImageStringData(true);
            $imageType = $end_element->getImageType() ? $end_element->getImageType() : 'image/jpg';
            $imageData = 'data:' . $imageType . ';base64,' . str_replace(array("\r\n", "\r", "\n"), "", $imageDataTmp);

            //保存文件
            //$imageSrc = './uploads/' . md5($end_element->getSource()) . '.' . $end_element->getImageExtension();
            //file_put_contents($imageSrc,base64_decode(explode(',',$imageData)[1]));

            $html .= '<img src="' . $imageData . '" style="width:100%;height:auto">';
        }
        return $html;
    }

    /**
     * 获取word文档内容
     * @param string $path
     * @return array
     */
    public static function getWord($path = '')
    {
        //加载word文档，使用phpword处理
        $phpWord = \PhpOffice\PhpWord\IOFactory::load($path);


//        print_R($phpWord);exit();
        return self::getNodeContent($phpWord);
    }

    /**
     * 根据word主节点获取分节点内容
     * @param $word
     * @return array
     */
    public static function getNodeContent($word)
    {
        $return = [];
        //分解部分
        foreach ($word->getSections() as $section)
        {
            if ($section instanceof \PhpOffice\PhpWord\Element\Section) {
                //分解元素
                foreach ($section->getElements() as $element)
                {



                    //文本元素
                    if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) {

                        $text = '';
                        foreach ($element->getElements() as $ele) {
                            $text .= self::getTextNode($ele);
                        }
                        $return[] = $text;
                    }
                    //表格元素
                    else if ($element instanceof \PhpOffice\PhpWord\Element\Table) {
                        foreach ($element->getRows() as $ele)
                        {
                            $return[] = self::getTableNode($ele);
                        }
                    }
                    //保留文本元素
                    else if ($element instanceof \PhpOffice\PhpWord\Element\PreserveText) {

                        //当是预留文本的时候
                        $text='';
                        foreach ($element->getText() as $ele=>$value)
                        {
                            $text .= $value;
                        }
                        $return[] = $text;
                    }
                }
            }
        }
        return $return;
    }

    /**
     * 获取文档节点内容
     * @param $node
     * @return string
     */
    public static function getTextNode($node)
    {
        $return = '';
        //处理文本
        if ($node instanceof \PhpOffice\PhpWord\Element\Text)
        {
            $return .= $node->getText();
        }
        //处理图片
        else if ($node instanceof \PhpOffice\PhpWord\Element\Image)
        {
            $return .= self::pic2text($node);
        }
        //处理文本元素
        else if ($node instanceof \PhpOffice\PhpWord\Element\TextRun) {
            foreach ($node->getElements() as $ele) {
                $return .= self::getTextNode($ele);
            }
        }//处理保留文本
        else if ($node instanceof \PhpOffice\PhpWord\Element\PreserveText) {
            $return .= $node->getText();
        }
        return $return;
    }

    /**
     * 获取表格节点内容
     * @param $node
     * @return string
     */
    public static function getTableNode($node)
    {
        $return = '';
        //处理行
        if ($node instanceof \PhpOffice\PhpWord\Element\Row) {
            foreach ($node->getCells() as $ele)
            {
                $return .= self::getTableNode($ele);
            }
        }
        //处理列
        else if ($node instanceof \PhpOffice\PhpWord\Element\Cell) {
            foreach ($node->getElements() as $ele)
            {
                $return .= self::getTextNode($ele);
            }
        }
        return $return;
    }

    /**
     * 处理word文档中base64格式图片
     * @param $node
     * @return string
     */
    public static function pic2text($node)
    {
        //获取图片编码
        $imageData = $node->getImageStringData(true);
        //添加图片html显示标头
        $imageData = 'data:' . $node->getImageType() . ';base64,' . $imageData;
        $return = '<img src="'.$imageData.'">';
        return $return;
    }
    /**
     * 处理word文档中base64格式图片
     * @param $node
     * @return string
     */
    public static function pic2file($node)
    {
        //图片地址(一般为word文档地址+在word中的锚点位置)
        $imageSrc  = 'images/' . md5($node->getSource()) . '.' . $node->getImageExtension();
        $imageData = $node->getImageStringData(true);
        //将图片保存在本地
        file_put_contents($imageSrc, base64_decode($imageData));
        return $imageSrc;
    }

    /**
     * 将word转化为html(转换存储html文件后展示)
     * @param $path
     * @throws \PhpOffice\PhpWord\Exception\Exception
     */
    // public static function word2html($path)
    // {
    //     $phpWord = FileImportService::getOne($path);
    //     //转为html处理
    //     $xmlWriter  = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, "HTML");
    //     $path = pathinfo($path);
    //     $fileName = $path['dirname'] . '/' . $path['filename'] . '.html';
    //     $xmlWriter->save($fileName);
    //     $html = file_get_contents($fileName);
    //     echo $html;
    //     die;
    //
    // }




    public function deleteFile($filePath)
    {
        if (file_exists($filePath)) {
            $tt=unlink($filePath);

            return $tt;
        }
        else {

            return false;
        }

    }

}
